package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONArray;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /*首页店铺类型*/
    @Override
    public Result selectShopType() {
        String key= RedisConstants.CACHE_SHOP_TYPE_KEY;
        /*先从redis里面获取*/
        String shopType = stringRedisTemplate.opsForValue().get(key);
        if(StrUtil.isNotBlank(shopType)){
            /*这里用的alibba的fastJson*/
            List<ShopType> shopTypes = JSONArray.parseArray(shopType, ShopType.class);
            return Result.ok(shopTypes);
        }
        /*redis里面没有，从数据库里面去查询*/
        List<ShopType> shopTypes = baseMapper.selectList(null);
        if(shopTypes.isEmpty()){
            return Result.fail("没有店铺分类信息");
        }
        /*将店铺分类信息转换为json*/
        /*这里用的是slibabba的fastJson*/
        String RedisJson = JSONArray.toJSONString(shopTypes);
        stringRedisTemplate.opsForValue().set(key,RedisJson,RedisConstants.CACHE_SHOP_TYPE_TTL, TimeUnit.MINUTES);
        return Result.ok(shopTypes);
    }

}
